<template>
    <div class="warp">
        <div class="msg">
            <div v-if="list.length">
              <div class="list">
                   <div class="item" v-if="detail.remark">
                    <img src="@/assets/images/message.svg">
                        <span>订单备注消息</span>
                        <span>{{detail.addtime}}：{{detail.remark}}</span>
               </div>
              </div>
                <div class="list" v-for="item in list" :key="item.id">
                   
                    <div class="item">
                        <img src="@/assets/images/message.svg">
                        <span>{{item.userName}}</span>
                        <span>{{item.addtime}}：{{item.content}}</span>
                        <template v-if="moreThan30(item)">
                            <span class="btn">
                                <van-button type="primary" size="mini" @click="handleShowEdit(item)">编辑</van-button>
                                <van-button type="danger" size="mini" @click="handleDelMsg(item.id)">删除</van-button>
                                <!-- <v-btn text color="primary" @click="handleShowEdit(item)">编辑</v-btn>
                                <v-btn text color="error" @click="handleDelMsg(item.id)">删除</v-btn> -->
                            </span>
                        </template>
                    </div>
                   
                    <template v-if="item.files && item.files.length">
                        <div class="subitem" v-for="file in item.files" :key="file.name">
                            <!-- <img v-if="file.filePath && file.filePath.indexOf('png') != -1 || file.filePath && file.filePath.indexOf('jpg') != -1" src="@/assets/images/img.png" alt="">
                            <img v-else-if="file.filePath && file.filePath.indexOf('docx') != -1" src="@/assets/images/docx.png" alt="">
                            <img v-else-if="file.filePath && file.filePath.indexOf('pdf') != -1" src="@/assets/images/pdf.png" alt="">
                            <img v-else-if="file.filePath && file.filePath.indexOf('xls') != -1" src="@/assets/images/xls.png" alt="">
                            <img v-else-if="file.filePath && file.filePath.indexOf('zip') != -1" src="@/assets/images/zip.png" alt="">
                            <img v-else src="@/assets/images/file.png" alt="">
                            <span style="margin-left: 10px">{{ file.name }} ({{file.size}}M)</span>
                            <van-button type="primary" size="mini" @click="seeFile(file.filePath)" style="margin-left:10px">查看</van-button>
                            <van-button type="primary" size="mini" @click="handleDown(file)">下载</van-button> -->

                            <div v-if="file.filePath && file.filePath.indexOf('png') != -1 || file.filePath && file.filePath.indexOf('jpg') != -1" >
                                <img src="@/assets/images/img.png" alt="">
                                <span style="margin-left: 10px">{{ file.name }} ({{file.size}}M)</span>
                                <van-button type="primary" size="mini" @click="handleImagePreview(file.filePath)" style="margin-left:10px">查看</van-button>
                            </div>
                        </div>
                    </template>
                </div>
                <div class="teggerNews">
                    <div v-if="total > 3 && !isAll" @click="getAllMsg">...展开所有动态</div>
                    <div v-else-if="total > 3 && isAll" @click="getSmallMsg">...收起所有动态</div>
                </div>
            </div>
            <Empty v-else :eStyle="{paddingTop: 0}" />
        </div>
        <div class="add">
            <van-field
                v-model="addmsg.content"
                rows="1"
                autosize
                maxlength="500"
                type="textarea"
                placeholder="请输入任务动态，有文本信息信息才能发布"
            />
            <!-- <v-textarea
                v-model="addmsg.content"
                auto-grow
                label="请输入任务动态，有文本信息信息才能发布"
                rows="2"
                row-height="20"
            ></v-textarea> -->
            
            <div class="files" v-for="(item, index) in uploadFiles" :key="item.name">
                <div class="f-text">{{item.name}} ({{item.size}}M)</div>
                <!-- <span style="margin-left: 50px"> -->
                    <van-button type="primary" size="mini" @click="seeFile(item.filePath)" style="flex-shrink: 0">查看</van-button>
                    <van-button type="danger" size="mini" @click="uploadFiles.splice(index, 1)" style="flex-shrink: 0">删除</van-button>
                    <!-- <v-btn text color="primary" @click="seeFile(item.filePath)">查看</v-btn>
                    <v-btn text color="error" @click="uploadFiles.splice(index, 1)">删除</v-btn> -->
                <!-- </span> -->
            </div>
            <div class="send-warp">
                <!-- <img src="@/assets/images/appendix.svg" alt=""> -->
                <!-- <van-uploader 
                    :after-read="afterRead" 
                    :max-size="100 * 1024 * 1024" 
                    @oversize="onOversize" 
                    accept="video/*,image/*,.pdf,.doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.xlsx,.zip,.mp4"
                >
                    <span style="color:#48a1fa">添加附件</span>
                </van-uploader> -->
                <van-checkbox-group v-if="type === 'order' && user.uid === detail.scheduleId" v-model="check" direction="horizontal" style="margin-left: 0.5rem">
                    <van-checkbox name="order" icon-size="0.3rem">指挥可见</van-checkbox>
                    <van-checkbox name="task" icon-size="0.3rem">飞手可见</van-checkbox>
                </van-checkbox-group>
                <span class="send-btn"><van-button type="primary" size="mini" @click="sendMsg">发送</van-button></span>
                <!-- <v-btn color="primary" style="float: right" @click="sendMsg">发送</v-btn> -->
            </div>
        </div>

        <van-dialog v-model="edit.show" title="编辑消息" confirm-button-color="#1976d2" show-cancel-button @confirm="handleEditMsg">
            <van-field
                v-model="edit.form.content"
                rows="1"
                autosize
                label=""
                type="textarea"
                placeholder="请输入动态消息"
            />
        </van-dialog>
        
    </div>
</template>

<script>
import Empty from '../../../components/Empty'
import { TaskMsgList, TaskMsgCreate, DelMsg, EditMsg } from '../../../api/task'
import { UploadOss } from '../../../api/common'
import moment from 'moment'
import { Toast, Dialog, ImagePreview } from 'vant'

export default {
    props: ['type', 'detail'],
    components: {
        // vanField: Field,
        // vanUploader: Uploader,
        Empty,
        [Dialog.Component.name]: Dialog.Component,
        [ImagePreview.Component.name]: ImagePreview.Component
    },
    data(){
        return {
            taskId: '',
            list: [],
            pagination: {
                pageNo: 1,
                pageSize: 3
            },
            total: 0,
            isAll: false,
            addmsg: {
                content: undefined,
                files: [],
                isOrder: 0,
                isPilot: 1,
                taskId: undefined
            },
            uploadFiles: [],
            edit: {
                show: false,
                form: {
                    id: undefined,
                    content: undefined,
                    files: [],
                    isOrder: undefined,
                    isPilot: undefined
                }
            },
            user: {},
            check: ['order', 'task']
        }
    },
    filters: {
        filterData(val){
            if(val){
                return moment(val).format('YYYY-MM-DD HH:ss')
            }else{
                return '未知日期'
            }
        }
    },
    methods: {
        async getTaskMsgList(){
            let { taskId, pagination, type } = this,
                { data: { data, totalCount }} = await TaskMsgList({ taskId, ...pagination, type: type === 'pilot' ? 1 : 0 })
            
            this.list = (data || []).map(item => {
                return {
                    ...item,
                    files: (item.files && item.files != 'null') ? JSON.parse(item.files): []
                }
            })
            console.log('list', this.list)
            this.total = totalCount
        },
        getAllMsg(){
            this.pagination.pageSize = 100
            this.getTaskMsgList()
            this.isAll = true
        },
        getSmallMsg(){
            this.pagination.pageSize = 3
            this.getTaskMsgList()
            this.isAll = false
        },
        async afterRead(data){
            console.log(data)
            let { file } = data
            let formData = new FormData()
            formData.append('uploadFile', file)
            let { data: {filePath} } = await UploadOss(formData)
            let size = file.size / 1024 / 1024
            this.uploadFiles.push({
                filePath,
                name: file.name,
                size: size < 0.1 ? 0.1 : size.toFixed(1),
            })
            if(!this.addmsg.content){
                this.addmsg.content = file.name
            }
        },
        handleImagePreview(url) {
            ImagePreview({
                images:[url], 
                closeable: true, // 关闭按钮
                showIndex: false // 页码
            })
        },
        seeFile(url){
            window.open(url)
        },
        async sendMsg(){
            console.log(this.user)
            console.log(this)
            let { addmsg, uploadFiles, type, check } = this
                // addmsg.files = uploadFiles.map(item => item.filePath)
            if(!addmsg.content){
                return Toast('请输入任务动态')
            }
            addmsg.files = uploadFiles
            if(type === 'order'){
                addmsg.isOrder = check.includes('order') ? 1 : 0
                addmsg.isPilot = check.includes('task') ? 1 : 0
            }else{
                addmsg.isOrder = type === 'pilot' ? 0 : 1
                addmsg.isPilot = type === 'pilot' ? 1 : 0
            }
                
            let { status } = await TaskMsgCreate(addmsg)
            if(status === 1){
                Toast.success('添加成功')
                this.addmsg.content = undefined
                this.uploadFiles = []
                this.getTaskMsgList()
            }else{
                Toast.fail('添加失败！')
            }
        },
        handleDelMsg(id){
            Dialog.confirm({
                title: '删除',
                message: '是否删除该条消息？',
            })
            .then(async () => {
                let { status } = await DelMsg(id)
                if(status === 1){
                     Toast.success('删除成功')
                     this.getTaskMsgList()
                }else{
                    Toast.fail('删除失败！')
                }
            })
            .catch(err => { console.log(err)})
        },
        handleShowEdit(item){
            let { form } = this.edit
            Object.keys(form).forEach(k => {
                form[k] = item[k]
            })
            // this.edit.form.id = id
            this.edit.form = form
            // this.edit.form.content = content
            this.edit.show = true
        },
        async handleEditMsg(){
            let { form } = this.edit,
                { status } = await EditMsg({ ...form })
            if(status === 1){
                Toast.success('修改成功')
                this.getTaskMsgList()
            }else{
                Toast.fail('修改失败！')
            }
        },
        handleDown(file){
            window.open(file.filePath)
            // let link = document.createElement('a')  // 创建a标签
            // link.style.display = 'none'
            // link.href = file.filePath // 设置下载地址
            // link.setAttribute('download', '') // 添加downLoad属性
            // document.body.appendChild(link)
            // link.click()
        },
        moreThan30(item){
            let { addtime, userId, type } = item,
                { user } = this
            const now = moment()
            const add = moment(addtime)
            const diff =now - add
            const min30 = 30 * 60 * 1000 //三十分钟
            if(diff < min30 && user.uid == userId && type === 0){
                return true
            }else{
                return false
            }
        },
        onOversize(file){
            console.log(file)
            Toast('文件大小不能超过 100M');
        }
    },
    created(){
        this.taskId = this.addmsg.taskId = this.$route.params.id
        let u = localStorage.getItem('userInfo')
        this.user = u ? JSON.parse(u) : {}
        this.getTaskMsgList()
    }
}
</script>

<style lang="scss" scoped>
    .warp{
        padding: .4rem;
        font-size: .293333rem;
        text-align: left;
        .list{
            margin-bottom: .133333rem;
            .item{
                display: flex; 
                // position: relative;
                // align-items: center;
                > img{
                    width: .586667rem;
                    height: .586667rem;
                }
                > span:nth-of-type(1){
                    flex-shrink: 0;
                    margin-left: .2rem;
                }
                > span:nth-of-type(2){
                    margin-left: .333333rem;
                    padding-right: .2rem;
                    word-break: break-all;
                    line-height: 0.4rem;
                }
                .btn{
                    flex-shrink: 0;
                }
            }  
            .subitem{
                padding-left: .8rem;
                display: flex;
                // align-items: center;
                margin-bottom: .066667rem;
                > span{
                    word-break: break-all;
                    line-height: .4rem;
                }
                .van-button{
                    flex-shrink: 0;
                }
                img{
                    width: .533333rem;
                    height: .533333rem;
                }
            }
        }
        .msg{
            position: relative;
            border: 1px #ccc solid;
            // border-radius: 10px;
            padding: .266667rem .2rem;
            max-height: 6.333333rem;
            overflow-y: auto;
            // .teggerNews{
            //     position: fixed;
            //     bottom: 0;
            //     left: 0;
            //     width: 100%;
            // }
        }
        .add{
            border: 1px #ccc solid;
            padding: .333333rem;
            margin-top: .266667rem;
            .van-cell{
                padding: 0;
                font-size: .293333rem;
                padding-bottom: .066667rem;
                margin-bottom: .066667rem;
            }
            .files{
                display: flex;
                align-items: center;
                margin: .066667rem 0;
                .f-text{
                    word-break: break-all;
                }
                ::v-deep{
                    .van-button:nth-of-type(1){
                        margin-left: 1rem;
                    }
                }
            }
            .send-warp{
                position: relative;
                display: flex;
                align-items: center;
                padding-top: .2rem;
                > img{
                    margin-right: .2rem;
                }
                .send-btn{
                    position: absolute;
                    right: 0;
                }
            }
        }
    }
</style>